package com.ys.controller.api.administration;

import com.ys.entity.administration.AdmSignetManage;
import com.ys.entity.administration.AdmUseSignetApply;
import com.ys.entity.sys.YsCol;
import com.ys.service.administration.AdmUseSignetApplyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

@Controller
@RequestMapping("/api/inter/admUseSignetApply")
public class ApiInterAdmUseSignetApplyController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterAdmUseSignetApplyController.class);
    private static Long MENU_ID = 10166L;

    @Autowired
    private CommonApiService<AdmUseSignetApply> commonApiService;
    @Autowired
    private AdmUseSignetApplyService admUseSignetApplyService;
    @Autowired
    private YspTaskService yspTaskService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public AdmUseSignetApply setSeachSql(AdmUseSignetApply cond){
        cond.addField("U.UserId + '/' + U.UserName AS createUserNameTxt ");
        cond.addField("U.RoleName  AS createPostName ");
        cond.addField("U.DeptName  AS createDeptName ");
        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId");
        //排序
        cond.setOrderby("A.UpdateTime DESC");
        cond = commonApiService.dataAuth(MENU_ID, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("admUseSignetApply:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute AdmUseSignetApply cond
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询印章申请表出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequiresPermissions("admUseSignetApply:export")
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute AdmUseSignetApply cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MENU_ID)
                    .where("A.Code != 'ope'")
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<AdmUseSignetApply> util = new ExportExcelUtils<>(new AdmUseSignetApply());
            String toFilePath = util.exportExcel(listData, listField, "印章申请表");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出印章申请表出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 参数验证
     */
    public String checkParams(Map<String, Object> params){
        logger.info("印章申请表单据信息："+params);
        Predicate<String> isNotNull = item-> item!=null && !"".equals(item.trim());//是否为空，返回：非空true，空false
        String backMsg = "";
        if(params==null){
            return "参数为空！";
        }
        if(!isNotNull.test(params.get("bid")+"")){
            return "单号为空！";
        }

        if(!isNotNull.test(params.get("purpose")+"")){
            return "请选择用途！";
        }
        if(!isNotNull.test(params.get("useTime")+"")){
            return "请选择用章时间！";
        }
        //借章（0）时必须填写还章时间
        if(params.get("purpose").toString().equals("0") && !isNotNull.test(params.get("backTime")+"")){
            return "借章时必须填写还章时间！";
        }
        if(!isNotNull.test(params.get("signetCode")+"")){
            return "印章编码为空！";
        }
        if(!isNotNull.test(params.get("signetName")+"")){
            return "印章名称为空！";
        }
        if(!isNotNull.test(params.get("signetTypeTxt")+"")){
            return "印章类型为空！";
        }
        if(!isNotNull.test(params.get("explain")+"")){
            return "请填写用章说明！";
        }
        if(params.get("explain").toString().length()>200){
            return "用章说明的数字不要大于200个字！";
        }
        AdmSignetManage admSignetManage = new AdmSignetManage().setCode(params.get("signetCode")+"").setSignetStatus(1).queryFirst();
        if(admSignetManage==null){
            return "选择的印章不存在或者已停用，请重新选择印章！";
        }
        Map<String,Object> admSignetManageIsUsed = new AdmSignetManage()
                .addField("CASE WHEN U.Bid IS NULL THEN '0' ELSE '1' END isUsed ")
                .addField("CONVERT(varchar(100), U.BackTime, 25) AS backTime ")
                .addLeftJoin("ADM_UseSignetApply U ON A.Code = U.SignetCode AND U.EffectStock = 0 AND U.Purpose = 0 ")
                .setCode(params.get("signetCode")+"")
                .queryFirstMap();
        if(admSignetManageIsUsed!=null && admSignetManageIsUsed.get("isUsed").toString().equals("1")){
            return "印章已借出，还章日"+ admSignetManageIsUsed.get("backTime");
        }
        return backMsg;

    }



    /**
     * 新增
     */
    @RequiresPermissions("admUseSignetApply:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //参数验证
            String errorMsg = checkParams(params);
            if(errorMsg!=null && !"".equals(errorMsg)){
                return R.error(errorMsg);
            }
            // 验证单号
            if (new AdmUseSignetApply().setBid(params.get("bid")+"").count() > 0) {
                return R.error("该单号已存在！");
            }
            return admUseSignetApplyService.add(params,MENU_ID);
        } catch (Exception e) {
            logger.error("新增印章申请表出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("admUseSignetApply:edit")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //参数验证
            String errorMsg = checkParams(params);
            if(errorMsg!=null && !"".equals(errorMsg)){
                return R.error(errorMsg);
            }
            return admUseSignetApplyService.update(params);
        } catch (Exception e) {
            logger.error("修改印章申请表出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 流转通过
     */
    //@RequiresPermissions("admUseSignetApply:flow")
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return admUseSignetApplyService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("印章申请表流转出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转驳回
     */
    //@RequiresPermissions("admUseSignetApply:flow")
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){

        AdmUseSignetApply entity = new AdmUseSignetApply().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("印章申请表流转驳回出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }

    /**
     * 流转驳回
     */
    //@RequiresPermissions("admUseSignetApply:flow")
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){

        AdmUseSignetApply entity = new AdmUseSignetApply().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("印章申请表流转驳回出错：",e.getMessage(),e);
            return R.error("服务器正在开小差，请联系客服");
        }
    }





    /**
     * 删除
     */
    //@RequiresPermissions("admUseSignetApply:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return admUseSignetApplyService.del(id);
        } catch (Exception e) {
            logger.error("删除印章申请表出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

}